#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: henry_oulen@163.com
@file: base.py
@time: 2023/11/8 15:49
@desc: 
"""

import base64
import random
import string
from datetime import datetime, timedelta
from io import BytesIO

import bcrypt
import jwt
from PIL import Image, ImageDraw, ImageFont

from backend.conf import config
from backend.conf.config import captcha_len, open_captcha
from backend.tvadmin.system.models.permission import User
from backend.tvadmin.utils.base_requeset import BaseHttpHandler
from backend.tvadmin.utils.base_response import SuccessResponse, ErrorResponse


class BaseHandler(BaseHttpHandler):
    '''
    用户登录
    post -> /login/
    payload:
        {
            "username": "用户名或者邮箱",
            "password": "密码"
        }
    '''

    def get(self, *args, **kwargs):
        """获取验证码"""
        captcha_text = ''.join(random.choices(string.ascii_uppercase + string.digits, k=captcha_len))
        # 创建图片对象
        image = Image.new('RGB', (120, 30), color=(255, 255, 255))
        draw = ImageDraw.Draw(image)
        font = ImageFont.truetype('arial.ttf', 25)
        key = str(config.snowflake.get_id())
        self.redis.set(key, captcha_text, expire_time=300)
        # 绘制验证码文本
        draw.text((10, 0), captcha_text, font=font, fill=(0, 0, 0))
        # 将图片转换为base64编码
        buffered = BytesIO()
        image.save(buffered, format="JPEG")
        img_str = base64.b64encode(buffered.getvalue()).decode()
        # 将base64编码的图片发送给客户端
        data = {
            "captcha_text": captcha_text,
            "captchaId": key,
            "captchaLength": captcha_len,
            "openCaptcha": open_captcha,
            "picPath": f"data:image/jpeg;base64,{img_str}"
        }
        return self.write(SuccessResponse(data=data))

    def post(self, *args, **kwargs):
        """
        登陆
        :param args: account 用户名 password 密码  captcha验证码  captchaId 验证码id  openCaptcha 是否开启防爆
        :param kwargs:
        :return:
        """
        account = self.request.data.get("account")
        password = self.request.data.get("password")
        captcha = self.request.data.get("captcha")
        captcha_id = self.request.data.get("captcha_id")
        # if captcha_id:
        #     captcha_value = self.redis.get(str(captcha_id))
        # else:
        #     return self.write(ErrorResponse(msg="验证码错误"))
        # if not captcha_value:
        #     return self.write(ErrorResponse(msg="验证码错误"))
        # if captcha_value != captcha:
        #     return self.write(ErrorResponse(msg="验证码错误"))

        # user_obj = User.query_first(filter=True,User.account=account)
        # user = User()
        # user_obj = User.query(filter="", User.id, User.name, User.account,
        #                       User.password)
        # user_obj = user_obj[0]
        user_obj = self.db.query(User).filter(User.account == account).first()
        data = {
            "is_super": 0,
            "token": ""
        }
        if user_obj:
            hashed_password = user_obj.password.encode("utf-8")
            if bcrypt.checkpw(password.encode('utf-8'), hashed_password):
                user_data = {
                    'id': user_obj.id,
                    'nick_name': user_obj.account,
                    "exp": datetime.utcnow() + timedelta(days=1)
                }
                token = jwt.encode(user_data, self.settings['secret_key'], algorithm=config.algorithm[0])
                # key = "authweb_" + str(user_obj.id)
                key = config.redis_auth_key + "pc" + str(user_obj.id)
                self.redis.set(key, token, expire_time=60 * 60 * 24)
                data = {
                    "is_super": 0,
                    "token": token
                }
        return self.write(SuccessResponse(data=data))


class Handler(BaseHttpHandler):
    '''
    用户登录
    post -> /login/
    payload:
        {
            "username": "用户名或者邮箱",
            "password": "密码"
        }
    '''

    def get(self, *args, **kwargs):
        return self.write(SuccessResponse())


class AuthMiddleware:
    def __init__(self, handler):
        self.handler = handler

    async def __call__(self, request):
        token = request.headers.get("Authorization")
        if token:
            try:
                payload = jwt.decode(token, "secret_key", algorithms=["HS256"])
                user = "abab"
                if user:
                    request.current_user = user
            except jwt.ExpiredSignatureError:
                request.current_user = None
        else:
            request.current_user = None
        return await self.handler(request)


class Register(BaseHttpHandler):
    def post(self, *args, **kwargs):
        """
        用户注册
        :param args:
        :param kwargs:
        :return:
        """
        password = self.request.data.get("password")
        if password:
            hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
            request_data = self.request.data
            request_data["password"] = hashed_password
            user_obj = User(**request_data)
            user = User.add(user_obj, self.request)
            return self.write(SuccessResponse(user))
